package cn.ibizlab.util.rest;

import cn.ibizlab.util.security.AuthenticationInfo;
import cn.ibizlab.util.security.AuthenticationUser;
import cn.ibizlab.util.security.AuthorizationLogin;
import cn.ibizlab.util.service.AuthenticationUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping(value = "/")
public class AppController {

	@Autowired
	private AuthenticationUserService userDetailsService;

	@PostMapping(value = "${ibiz.auth.path:v7/login}")
	public ResponseEntity<AuthenticationInfo> login(@Validated @RequestBody AuthorizationLogin authorizationLogin){
		userDetailsService.resetByUsername(authorizationLogin.getUsername());
		return ResponseEntity.ok().body(userDetailsService.loadUserByLogin(authorizationLogin.getUsername(),authorizationLogin.getPassword()));
	}

	@RequestMapping(method = {RequestMethod.GET,RequestMethod.POST}, value = "appdata")
	public ResponseEntity<Map<String,Object>> getAppData() {
		return ResponseEntity.status(HttpStatus.OK).body(userDetailsService.getAppData());
	}

    @RequestMapping(method = {RequestMethod.GET,RequestMethod.POST}, value = "${ibiz.auth.logoutpath:v7/logout}")
    public void logout() {
		if(AuthenticationUser.getAuthenticationUser()!=null){
			userDetailsService.resetByUsername(AuthenticationUser.getAuthenticationUser().getUsername());
    	}
    }

}
